/*
 * Copyright 2013 Ritwik.net.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jety.server;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import org.jety.commons.exception.JsonRpcClientException;
import org.jety.commons.exception.JsonRpcException;
import org.jety.commons.util.CommunicationUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Rivaldo
 */
public class AsynchronousHandler implements InvocationHandler {

    private static final Logger LOG = LoggerFactory.getLogger(AsynchronousHandler.class);

    private final int requestID;
    private final AsynchronousTransport transport;

    public AsynchronousHandler(int requestID, AsynchronousTransport transport) {
        this.requestID = requestID;
        this.transport = transport;
    }

    private void invoke(Method method, Object[] args) throws JsonRpcException {

        String requestMethod = CommunicationUtil.creatMethodRequest(requestID, "Async" + Integer.toString(requestID), method, args).toString();
        LOG.debug("JSON-RPC >>  {}", requestMethod);

        try {
            transport.writeResponse(requestMethod);
        } catch (Exception e) {
            LOG.error("Unable to get data from transport.", e);
            throw new JsonRpcClientException("Unable to get data from transport.", e);
        }
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        invoke(method, args);
        return null;
    }

}
